<template>
  <div class="page-content">
    <div class="header" style="margin-bottom: 1.5rem">
      <h3>角色权限</h3>
    </div>
    <el-row>
      <el-col :xs="24" :sm="12" :lg="6" class="el-col2">
        <el-button @click="showDialog('add')" v-ripple>新增角色</el-button>
      </el-col>
    </el-row>

    <art-table :data="tableData" :loading="tableLoading" :currentPage="pageNum" :pageSize="pageSize" :total="pageTotal"
      @current-change="currentChange" @size-change="sizeChange">
      <template #default>
        <el-table-column label="角色名称" prop="name" />
        <el-table-column label="角色编码" prop="code" align="center" />
        <el-table-column #default="scope" label="状态" align="center">
          <el-switch v-model="scope.row.status" :active-value="1" :inactive-value="0"
            @click="editStatus(scope.row.id, scope.row.status)" />
        </el-table-column>
        <el-table-column label="创建时间：" prop="createTime" align="center">
          <template #default="scope">
            {{ formatDate(scope.row.createTime) }}
          </template>
        </el-table-column>
        <el-table-column fixed="right" label="操作" width="100px">
          <template #default="scope">
            <el-row>
              <button-more :list="[
                { key: 'permission', label: '菜单权限' },
                { key: 'edit', label: '编辑角色' },
                { key: 'delete', label: '删除角色' }
              ]" @click="buttonMoreClick($event, scope.row)" />
            </el-row>
          </template>
        </el-table-column>
      </template>
    </art-table>

    <el-dialog v-model="dialogVisible" :title="dialogType === 'add' ? '新增角色' : '编辑角色'" width="30%"
      :close-on-click-modal="false">
      <el-form ref="formRef" :model="form" :rules="rules" label-width="120px">
        <el-form-item label="排序" prop="sort">
          <el-input v-model="form.sort" />
        </el-form-item>
        <el-form-item label="角色名称" prop="name">
          <el-input v-model="form.name" />
        </el-form-item>
        <el-form-item label="角色编码" prop="code">
          <el-input v-model="form.code" />
        </el-form-item>
        <el-form-item label="状态">
          <el-switch v-model="form.status" :active-value="1" :inactive-value="0" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit(formRef)">提交</el-button>
        </div>
      </template>
    </el-dialog>
    <el-dialog v-model="permissionDialog" title="权限分配" width="30%" :close-on-click-modal="false">
      <el-form ref="formRef" :model="form" :rules="rules" label-width="120px">
        <el-form-item label="菜单权限">
          <el-checkbox-group v-model="checkedCities">
            <el-checkbox :value="0" @change="toggleExpand">
              展开/折叠
            </el-checkbox>
            <el-checkbox :value="1" @change="toggleAllSelection">
              全选/全不选
            </el-checkbox>
            <el-checkbox :value="2">
              父子联动
            </el-checkbox>
          </el-checkbox-group>
          <el-tree ref="treeRef" :data="menuData" :props="defaultProps" node-key="id" show-checkbox
            :default-checked-keys="defaultCheckedKeys" :expand-on-click-node="false"
            :check-strictly="!parentChildLinkage" @check="handleCheckChange" highlight-current accordion
            style="width: 100%;" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="permissionDialog = false">取消</el-button>
          <el-button type="primary" @click="rolesHandleSubmit()">提交</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ButtonMoreItem } from '@/components/core/forms/ArtButtonMore.vue'
import { useMenuStore } from '@/store/modules/menu'
import { ElMessage, ElMessageBox } from 'element-plus'
import type { FormInstance, FormRules } from 'element-plus'
import { formatMenuTitle } from '@/router/utils/utils'
import { RolesList, AddRoles, EditRoles, EditStatus, DelRoles, getMenuInfoSimple, assignRoles, getRoleCodeList } from '@/api/driverSchoolApi'
import type { ElTree } from 'element-plus'

const dialogVisible = ref(false)
const permissionDialog = ref(false)
const menuList = computed(() => useMenuStore().getMenuList)
const isExpanded = ref(false)
const isAllSelected = ref(false)
const parentChildLinkage = ref(true)
const menuData = ref<any>([])
const treeRef = ref<InstanceType<typeof ElTree>>()
const checkedCities = ref([2])

const formRef = ref<FormInstance>()

const rules = reactive<FormRules>({
  name: [
    { required: true, message: '请输入角色名称', trigger: 'blur' },
    { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
  ],
  des: [{ required: true, message: '请输入角色描述', trigger: 'blur' }]
})

const form = reactive({
  id: Number(''),
  name: '',
  sort: '1',
  status: 1,
  code: ''
})

const dialogType = ref('add')

const showDialog = (type: string, row?: any) => {
  dialogVisible.value = true
  dialogType.value = type

  if (type === 'edit' && row) {
    form.id = row.id
    form.name = row.name
    form.code = row.code
    form.status = row.status
  } else {
    form.id = Number('')
    form.name = ''
    form.code = ''
  }
}

const buttonMoreClick = (item: ButtonMoreItem, row: any) => {
  if (item.key === 'permission') {
    showPermissionDialog(row)
  } else if (item.key === 'edit') {
    showDialog('edit', row)
  } else if (item.key === 'delete') {
    deleteRole(row.id)
  }
}

const roleId = ref('')
const codeId = ref('')
const showPermissionDialog = (row: any) => {
  permissionDialog.value = true
  roleId.value = row.id
  codeId.value = row.code
  getMenuInfo()
  allSelectRole()
}

const defaultProps = {
  children: 'children',
  label: 'label',
  isLeaf: 'isLeaf'
}

const deleteRole = (id: string) => {
  ElMessageBox.confirm('确定删除该角色吗？', '删除确认', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'error'
  }).then(async () => {
    const res = await DelRoles(id)
    if (res.code === '00000') {
      ElMessage.success('删除成功')
      getData()
    }
  })
}

const handleSubmit = async (formEl: FormInstance | undefined) => {
  if (!formEl) return

  await formEl.validate(async (valid) => {
    if (valid) {
      const message = dialogType.value === 'add' ? '新增成功' : '修改成功'
      if (dialogType.value === 'add') {
        let res = await AddRoles({
          name: form.name,
          code: form.code,
          sort: form.sort,
          status: form.status
        })
        if (res.code === '00000') {
          ElMessage.success(message)
          dialogVisible.value = false
          getData()
        }
      } else {
        let res = await EditRoles(form.id, {
          id: form.id,
          name: form.name,
          code: form.code,
          sort: form.sort,
          status: form.status
        })
        if (res.code === '00000') {
          ElMessage.success(message)
          dialogVisible.value = false
          getData()
        }
      }
    }
  })
}

async function editStatus(id: any, status: number) {
  try {
    const res = await EditStatus(id, status)
    if (res.code === '00000') {
    }
  } catch (e) {

  } finally {
    await getData()
  }
}

const formatDate = (date: string) => {
  return new Date(date)
    .toLocaleString('zh-CN', {
      year: 'numeric',
      month: '2-digit',
      day: '2-digit',
      hour: '2-digit',
      minute: '2-digit',
      second: '2-digit'
    })
    .replace(/\//g, '-')
}
const tableData = ref([])
const pageNum = ref(1)
const pageSize = ref(10)
const pageTotal = ref(0)
const tableLoading = ref(false)
const keywords = ref('')
async function getData() {
  try {
    tableLoading.value = true

    const { code, data } = await RolesList({
      pageNum: pageNum.value,
      pageSize: pageSize.value,
      keywords: keywords.value
    })
    if (code === '00000') {
      tableData.value = data.list
      pageTotal.value = data.total
    }
  } catch (e) {
  } finally {
    tableLoading.value = false
  }
}
const currentChange = (val: number) => {
  pageNum.value = val
  getData()
}

const sizeChange = (val: number) => {
  pageSize.value = val
  pageNum.value = 1
  getData()
}
const search = () => {
  getData()
}

const getMenuInfo = async () => {
  const res = await getMenuInfoSimple()
  if (res.code === '00000') {
    menuData.value = adaptToElTreeData(res.data)
    console.log(menuData.value);
  }
}

function adaptToElTreeData(originalData: any[]): any[] {
  return originalData.map(item => ({
    id: item.id,
    label: item.name,  
    children: item.children ? adaptToElTreeData(item.children) : undefined
  }));
}

// 展开/折叠切换
const toggleExpand = () => {
  isExpanded.value = !isExpanded.value
  toggleAllNodes(isExpanded.value)
}

// 全选/全不选切换
const toggleAllSelection = () => {
  isAllSelected.value = !isAllSelected.value
  if (isAllSelected.value) {
    treeRef.value?.setCheckedNodes(menuData.value)
    checkedIds.value = treeRef.value?.getCheckedKeys(false) || []
  } else {
    treeRef.value?.setCheckedNodes([])
    checkedIds.value = []
  }
}

// 展开/折叠所有节点
const toggleAllNodes = (expand: boolean) => {
  const nodes = treeRef.value?.store.nodesMap
  if (nodes) {
    for (const node in nodes) {
      nodes[node].expanded = expand
    }
  }
}

const checkedIds = ref<any>([])
// 处理复选框变化
const handleCheckChange = (data: any, checkedStatus: { checkedNodes: any }) => {
  // 更新全选状态
  isAllSelected.value = checkedStatus.checkedNodes.length === getAllNodes().length
  // 获取所有选中的id
  checkedIds.value = getCheckedIds()
}

// 获取所有节点
const getAllNodes = (): any => {
  const result: any = []
  const traverse = (nodes: any) => {
    nodes.forEach((node: any) => {
      result.push(node)
      if (node.children) {
        traverse(node.children)
      }
    })
  }
  traverse(menuData.value)
  return result
}

// 获取所有选中的id
const getCheckedIds = (): number[] => {
  // 获取所有选中的节点（半选和全选）
  if (!treeRef.value) return []
  // getCheckedKeys(true) 获取所有选中和半选的key，getCheckedKeys(false) 只获取全选的key
  return treeRef.value.getCheckedKeys(false) as number[]
}
const rolesHandleSubmit = async () => {
  const res = await assignRoles({
    roleId: roleId.value,
    menuIds: checkedIds.value
  })
  if (res.code === '00000') {
    ElMessage.success('分配成功')
    permissionDialog.value = false
  }
}

const defaultCheckedKeys = ref<string[]>([]) // 默认选中的节点key数组
const allSelectRole = async () => {
  const res = await getRoleCodeList({ codes: codeId.value })
  // 提取所有选中节点的id
  defaultCheckedKeys.value = res.data
  // 设置树形控件的选中状态
  nextTick(() => {
    if (treeRef.value) {
      treeRef.value.setCheckedKeys(defaultCheckedKeys.value)
    }
  })
}
onMounted(() => {
  getData()
})
</script>

<style lang="scss" scoped>
.page-content {
  .svg-icon {
    width: 1.8em;
    height: 1.8em;
    overflow: hidden;
    vertical-align: -8px;
    fill: currentcolor;
  }
}
</style>
